let express = require('express');
let router = express.Router();
let URL = require('url');
let mysql = require('mysql');
let bodyParser = require('body-parser');
let cookieParser = require('cookie-parser');
let session = require('cookie-session');
let mysqlhelp = require("../common/sql");
let jwt = require('jsonwebtoken'); // JWT
var utility = require("utility"); // md5加密
router.use(bodyParser.urlencoded({extended: true}));
// var User = require('./user'); // get

// 查看账号密码是否匹配
router.post('/getloginData', function (req, res, next) {
    let _user = req.body;
    let name = _user.username;
    let password = utility.md5(_user.password);
    let sql = 'select * from  admin_info where username = ? ';
    let parameter = name; // 请求的参数
    // select的promise方法执行完毕执行then方法
    mysqlhelp.select(sql, parameter).then(function (data) {
        let tokenContent = {name: name}; // 要生成token的主题信息
        let secretOrPrivateKey = "likaiji" // 这是加密的key（密钥）
        let token = jwt.sign(tokenContent, secretOrPrivateKey, {
            expiresIn: 60 * 30   // 半小时过期
        });
        // 用户名密码匹配
        if (data.result.length != 0 && data.result[0].password == password) {
            let updateTokensql = "update admin_info set token = ? where id= " + data.result[0].id + "";
            // 存储token
            mysqlhelp.select(updateTokensql, token).then(function (data) {
                console.log(data)
            }).catch(function (err) {
                console.log(err)
            })
            data.isEffective = true;
            res.send({'status': true, 'msg': '登陆成功', 'token': token, 'username': name})     //反给前台
        } else {
            data.isEffective = true;
            res.send({'status': false, 'msg': '用户名或密码错误！'});
            // data.isError = true;
            //             // data.response = "用户名或密码错误！"
        }
        // res.send(data)
    }).catch(function (err) {
        res.send({'status': false, 'msg': err, 'isEffective': true});
    })
});

// 校验token
router.post('/validateToken', (req, res, next) => {
    // console.log(req.body)
    let _user = req.body;
    let username = _user.username;
    let token = _user.token;
    let secretOrPrivateKey = "likaiji"; // 这是加密的key（密钥）
    jwt.verify(token, secretOrPrivateKey, (err, decode) => {
        if (decode) {  // 正确token
            res.send({'status': true, 'message': "token有效，可以继续使用", tokenMessage: decode, 'isEffective': true});
        } else { //  时间失效的时候/ 伪造的token
            res.send({'status': false, 'message': "token失效，请重新登录", tokenMessage: err, 'isEffective': true});

        }
    })
})

module.exports = router;

